﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace KD.DataImport
{
    public partial class frmImport : Form
    {
        private string E_PackingPath = string.Empty;
        private DataTable E_Source = null;
        private List<string> E_ListDataFile;
        private List<ImagePath> E_ListImages;
        bool E_ImportAllowed = false;
        List<SamplingInfo> E_ListSamplingInfo;
        private static string _strDasUser = System.Configuration.ConfigurationManager.AppSettings["DasUser"];
        private static string _strDasPassword = System.Configuration.ConfigurationManager.AppSettings["DasPassWord"];

        public frmImport()
        {
            InitializeComponent();
        }

        private void tools_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                case "Chose":
                    FolderBrowserDialog dialog = new FolderBrowserDialog();
                    dialog.Description = "请选择文件路径";
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        E_PackingPath = dialog.SelectedPath;
                        txtPath.Text = E_PackingPath;
                        DoBindDataFile();
                    }
                    break;
                case "Import":
                    if (E_ImportAllowed)
                    {
                        Thread _thImport = new Thread(new ThreadStart(DoImport)) { IsBackground = true };
                        _thImport.Start();
                    }
                    else
                        MessageBox.Show("请选择需要导入的数据！");
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void DoImport()
        {
            bool _bIsError = false;
            Image _imgBegin, _imgEnd;
            string _strImgNameBegin, _strImgNameAfter;
            RequestResult _modelResult = null;
            ImagePath _ipBegin, _ipEnd;
            int _iStep = 0;
            foreach (SamplingInfo model in E_ListSamplingInfo)
            {
                try
                {
                    _strImgNameBegin = model.Sampling_Id + "Before.jkdg";
                    _strImgNameAfter = model.Sampling_Id + "After.jkdg";
                    _ipBegin = E_ListImages.Find(c => c.E_FileName.Equals(_strImgNameBegin));
                    _ipEnd = E_ListImages.Find(c => c.E_FileName.Equals(_strImgNameAfter));

                    _imgBegin = ImageHelper.DoGetImageFromFile(_ipBegin == null ? string.Empty : _ipBegin.E_Path);
                    _imgEnd = ImageHelper.DoGetImageFromFile(_ipEnd == null ? string.Empty : _ipEnd.E_Path);

                    model.Img_Begin = _imgBegin == null ? string.Empty : ImageHelper.DoGetBase64FromImage(_imgBegin);
                    model.Img_End = _imgEnd == null ? string.Empty : ImageHelper.DoGetBase64FromImage(_imgEnd);

                    _modelResult = UploadMain.Instance.DoUploadSamplingInfo(model.Car_NO, model.FLowid, model.TotalLength, 0, model.CarriageLength, model.CarriageWidth, model.CarriageHeight, model.CarriagePostions,
                        model.BatchDate, model.Kind_Name, model.Material_Name, model.Supplier_Name, model.Unit_Name,
                      model.Device, model.Sample_Pail, model.Pos_Count, model.LayoutType, model.Sampling_Time, model.Sampling_Time_End, model.Sampling_State, model.SampleWeight, model.SampleRfid, model.SamplingPos, model.Img_Begin, model.Img_End,
                      _strDasUser, _strDasPassword);
                    //上传一条记录到三级编码系统
                    if (_modelResult.En_Success)
                        KD.Sms.UI.FormHelper.RicMsgShow(ricMsg, Sms.UI.MsgType.Information, string.Format("车号:{0}数据导入成功", model.Car_NO));
                    else
                        KD.Sms.UI.FormHelper.RicMsgShow(ricMsg, Sms.UI.MsgType.Error, string.Format("车号:{0}数据导入失败，原因:{1}", model.Car_NO, _modelResult.En_ErrInfo));
                    DoSetGridStyle(gridMain, _iStep, _modelResult.En_Success);
                    System.Threading.Thread.Sleep(100);
                }
                catch (Exception ex)
                {
                    KD.Sms.UI.FormHelper.RicMsgShow(ricMsg, Sms.UI.MsgType.Error, string.Format("往三级编码导入采样数据出现未知异常 车号:{0}", model.Car_NO));
                    Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Interface, string.Format("往三级编码导入采样数据出现未知异常 车号:{0}", model.Car_NO));
                    Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Interface, ex.ToString());
                    _bIsError = true;
                }
                System.Threading.Thread.Sleep(100);
                _iStep++;
            }
            if (_bIsError)
                Sms.UI.FormHelper.RicMsgShow(ricMsg, Sms.UI.MsgType.Error, string.Format("导入操作完成，在数据导入过程中出现错误..."));
            else
                Sms.UI.FormHelper.RicMsgShow(ricMsg, Sms.UI.MsgType.Information, string.Format("导入操作完成"));
        }

        private delegate void BindGrid(DataGridView grid, int index, bool isError);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        public static void DoSetGridStyle(DataGridView grid, int index, bool isError)
        {
            if (grid != null && !grid.IsDisposed)
            {
                //在线程里以安全方式调用控件
                if (grid.InvokeRequired)
                {
                    BindGrid _MyInvoke = new BindGrid(DoSetGridStyle);
                    grid.Invoke(_MyInvoke, new object[] { grid, index, isError });
                }
                else
                {
                    if (!isError)
                        grid.Rows[index].DefaultCellStyle.ForeColor = Color.Red;
                    else
                        grid.Rows[index].DefaultCellStyle.BackColor = Color.Green;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void DoBindDataFile()
        {
            E_ListDataFile = new List<string>();
            DoFindDataFile(new DirectoryInfo(E_PackingPath));
            listDataFile.DataSource = E_ListDataFile;
            if (E_ListDataFile != null && E_ListDataFile.Count == 1)
            {
                listDataFile.SelectedIndex = 0;
                DoShowDataFromFile();
            }
        }

        /// <summary>
        /// 递归查找所有数据文件
        /// </summary>
        /// <param name="diTotal"></param>
        private void DoFindDataFile(DirectoryInfo diTotal)
        {
            foreach (var _file in diTotal.GetFiles())
            {
                if (_file.FullName.IndexOf(".mkd") > 0)
                    E_ListDataFile.Add(_file.FullName);
            }

            if (diTotal.GetDirectories().Length > 0)
            {
                foreach (var _diChild in diTotal.GetDirectories())
                {
                    DoFindDataFile(_diChild);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmImport_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listDataFile_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            DoShowDataFromFile();
        }

        private void DoShowDataFromFile()
        {
            if (listDataFile.SelectedItem != null)
            {
                string _strFile = listDataFile.SelectedItem.ToString();
                string _strData = DesEncrypt.Decrypt(File.ReadAllText(_strFile));
                //反序列响应数据到具体的业务响应实体对象
                JsonSerializerSettings jsonSet = new JsonSerializerSettings();
                jsonSet.NullValueHandling = NullValueHandling.Ignore;
                E_ListSamplingInfo = JsonConvert.DeserializeObject<List<SamplingInfo>>(_strData, jsonSet);
                E_ListSamplingInfo.Sort((left, right) =>
                {
                    return left.Sampling_Id > right.Sampling_Id ? 1 : -1;
                });
                gridMain.DataSource = E_ListSamplingInfo;
                //加载所有图片
                E_ListImages = new List<ImagePath>();
                DoFindImageFile(new DirectoryInfo(E_PackingPath));
                E_ImportAllowed = true;
            }
        }

        /// <summary>
        /// 递归查找所有数据文件
        /// </summary>
        /// <param name="diTotal"></param>
        private void DoFindImageFile(DirectoryInfo diTotal)
        {
            foreach (var _file in diTotal.GetFiles())
            {
                if (_file.FullName.IndexOf(".jkdg") > 0)
                    E_ListImages.Add(new ImagePath(_file.FullName, _file.Name));
            }

            if (diTotal.GetDirectories().Length > 0)
            {
                foreach (var _diChild in diTotal.GetDirectories())
                {
                    DoFindImageFile(_diChild);
                }
            }
        }


    }


    /// <summary>
    /// 
    /// </summary>
    public class ImagePath
    {
        public ImagePath(string path, string filename)
        {
            E_Path = path;
            E_FileName = filename;
        }
        public string E_Path { set; get; }
        public string E_FileName { set; get; }
    }
}
